import requests
import json
import urllib.parse
import urllib.parse
from lxml import etree
import re
class Csdn:

    def searchUserInfo(self,uname: str):

        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42'
        }
        params = {
            "q": uname,
            "t": "userinfo",
            "p": "1",
            "s": "0",
            "tm": "0",
            "lv": "-1",
            "ft": "0",
            "l": "",
            "u": "",
            "ct": "-1",
            "pnt": "-1",
            "ry": "-1",
            "ss": "-1",
            "dct": "-1",
            "vco": "-1",
            "cc": "-1",
            "sc": "-1",
            "akt": "-1",
            "art": "-1",
            "ca": "-1",
            "prs": "",
            "pre": "",
            "ecc": "-1",
            "ebc": "-1",
            "ia": "1",
            "dId": "",
            "cl": "-1",
            "scl": "-1",
            "tcl": "-1",
            "platform": "pc",
            "ab_test_code_overlap": "",
            "ab_test_random_code": ""
        }

        url = 'https://so.csdn.net/api/v3/search?' + urllib.parse.urlencode(params)
        resp = requests.get(url=url, headers=headers)
        json_data = json.loads(resp.text)
        user_list = json_data['result_vos']
        # print(resp.text)

        for i in user_list:
            s=i['nickname']
            s = re.sub("<em>", "", s)
            s = re.sub("</em>", "", s)
            if s==uname:
                return i['username']
           # print('nickname:', s, 'userid:', i['userid'], 'user_url', i['user_url'])
        return -1


    def Midinfo(self,mid):
        url = f'https://blog.csdn.net/{mid}?type=blog'
        header = {
            'Host': 'blog.csdn.net',
            'Referer': 'https://blog.csdn.net/?spm=1000.2115.3001.4477',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42'
        }
        resp = requests.get(url=url, headers=header)
        pattern = r'IP 属地：(.*?)<'
        result = re.search(pattern, resp.text)
      #  print(result.group(1))
        dom =  etree.HTML(resp.text)
        try:
            result = dom.xpath('//meta[@name="description"]/@content')[0]
        except:
            return -1
        #print(result)
       # print(resp.text)
        return result

csdn=Csdn()
# print(csdn.searchUserInfo('momosheng10'))
# #
# # #
# print(csdn.Midinfo(csdn.searchUserInfo("6x6x6x")))

